<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fitness Keep - 健身社区</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .nav-bar {
            background: #f8f9fa;
            padding: 10px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .nav-links {
            display: flex;
            gap: 20px;
        }

        .nav-link {
            color: #667eea;
            text-decoration: none;
            font-weight: bold;
            padding: 8px 16px;
            border-radius: 4px;
            transition: all 0.3s ease;
        }

        .nav-link:hover {
            background: #667eea;
            color: white;
        }

        .nav-link.active {
            background: #667eea;
            color: white;
        }

        .content {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .feature-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .feature-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        .feature-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
        }

        .feature-description {
            color: #666;
            margin-bottom: 20px;
            line-height: 1.5;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-info {
            background: #17a2b8;
            color: white;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #667eea;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        .login-section {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }

        input[type="text"],
        input[type="password"],
        input[type="number"],
        input[type="date"],
        select,
        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }

        textarea {
            resize: vertical;
            min-height: 80px;
        }

        .result {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            font-weight: bold;
        }

        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .hidden {
            display: none;
        }

        /* 社区页面样式 */
        .community-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .form-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .post-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .post-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .post-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin: 0;
        }

        .post-meta {
            color: #666;
            font-size: 12px;
        }

        .post-content {
            color: #333;
            line-height: 1.6;
            margin-bottom: 15px;
        }

        .post-stats {
            display: flex;
            gap: 20px;
            margin-bottom: 15px;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }

        .stat-item {
            display: flex;
            align-items: center;
            gap: 5px;
            color: #666;
            font-size: 14px;
        }

        .stat-icon {
            font-size: 16px;
        }

        .stat-count {
            font-weight: bold;
            color: #333;
        }

        .post-actions {
            display: flex;
            gap: 15px;
            border-top: 1px solid #eee;
            padding-top: 15px;
        }

        .action-btn {
            background: none;
            border: none;
            color: #667eea;
            cursor: pointer;
            font-size: 14px;
            padding: 5px 10px;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        .action-btn:hover {
            background: #f0f0f0;
        }

        .action-btn.liked {
            color: #e74c3c;
        }

        .action-btn.favorited {
            color: #f39c12;
        }

        .action-btn .action-icon {
            margin-right: 5px;
        }

        .action-btn .action-text {
            margin-right: 8px;
        }

        .action-btn .action-count {
            background: #f0f0f0;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 12px;
            font-weight: bold;
        }

        .action-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .comments-section {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }

        .comment {
            background: #f8f9fa;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 4px;
        }

        .comment-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }

        .comment-author {
            font-weight: bold;
            color: #333;
        }

        .comment-time {
            color: #666;
            font-size: 12px;
        }

        .comment-content {
            color: #333;
            line-height: 1.6;
            margin-bottom: 10px;
        }

        .comment-actions {
            display: flex;
            gap: 10px;
            padding-top: 8px;
            border-top: 1px solid #eee;
        }

        .comment-form {
            margin-top: 10px;
        }

        .comment-input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
            box-sizing: border-box;
        }

        .loading {
            text-align: center;
            color: #666;
            padding: 20px;
        }

        .post-author {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .post-author .user-avatar {
            width: 40px;
            height: 40px;
            margin-right: 10px;
        }

        .form-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
            resize: vertical;
            min-height: 100px;
        }

        /* 个人信息页面样式 */
        .profile-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .profile-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .profile-info {
            max-width: 500px;
        }

        .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .info-row:last-child {
            border-bottom: none;
        }

        .info-label {
            font-weight: bold;
            color: #333;
            min-width: 80px;
        }

        .info-value {
            color: #666;
            text-align: right;
            flex: 1;
            margin-left: 20px;
        }

        select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }

        input[type="number"],
        input[type="date"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }

        /* 饮食分析页面样式 */
        .diet-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .diet-controls {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .nutrition-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .nutrition-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 15px;
        }

        .nutrition-item {
            text-align: center;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }

        .nutrition-label {
            display: block;
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
        }

        .nutrition-value {
            display: block;
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }

        .nutrition-unit {
            display: block;
            font-size: 12px;
            color: #999;
        }

        .food-list {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 15px;
        }

        .food-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .food-item:hover {
            background: #f0f0f0;
        }

        .food-item.selected {
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
        }

        .food-item-name {
            font-weight: bold;
            color: #333;
        }

        .food-item-nutrition {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }

        .diet-record-item {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .diet-record-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .diet-record-food {
            font-weight: bold;
            color: #333;
        }

        .diet-record-meal {
            background: #e3f2fd;
            color: #1976d2;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
        }

        .diet-record-nutrition {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            font-size: 12px;
            color: #666;
        }

        .diet-record-nutrition span {
            text-align: center;
        }

        /* 运动记录样式 */
        .exercise-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .exercise-card {
            background: #fff;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        #ongoingExercisesContainer {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .exercise-card.ongoing {
            border-left: 4px solid #28a745;
        }

        .exercise-card.completed {
            border-left: 4px solid #6c757d;
        }

        .health-status {
            font-weight: bold;
        }

        .health-status.normal {
            color: #28a745;
        }

        .health-status.warning {
            color: #ffc107;
        }

        .health-status.caution {
            color: #fd7e14;
        }

        .health-status.danger {
            color: #dc3545;
        }

        .health-status.critical {
            color: #721c24;
            background-color: #f8d7da;
            padding: 2px 6px;
            border-radius: 4px;
        }

        .exercise-status {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .status-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 6px;
        }

        .status-label {
            font-weight: 600;
            color: #495057;
        }

        .status-value {
            color: #007bff;
            font-weight: 500;
        }

        .exercise-actions {
            text-align: center;
        }

        .exercise-list {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            margin-top: 10px;
        }

        .exercise-item {
            padding: 12px 15px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .exercise-item:hover {
            background-color: #f8f9fa;
        }

        .exercise-item.selected {
            background-color: #e3f2fd;
            border-left: 4px solid #2196f3;
        }

        .exercise-item-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
        }

        .exercise-item-category {
            font-size: 12px;
            color: #666;
        }

        .exercise-item-description {
            font-size: 12px;
            color: #888;
            margin-top: 4px;
        }

        .exercise-records {
            margin-top: 30px;
        }

        .records-filter {
            margin-bottom: 15px;
        }

        .records-filter select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: #fff;
        }

        .records-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .exercise-record-item {
            background: #fff;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .exercise-record-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .exercise-record-name {
            font-weight: 600;
            color: #333;
        }

        .exercise-record-status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .exercise-record-status.ongoing {
            background: #fff3cd;
            color: #856404;
        }

        .exercise-record-status.completed {
            background: #d4edda;
            color: #155724;
        }

        .exercise-record-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            font-size: 14px;
        }

        .exercise-record-detail {
            display: flex;
            justify-content: space-between;
        }

        .exercise-record-label {
            color: #666;
        }

        .exercise-record-value {
            color: #333;
            font-weight: 500;
        }
    </style>
</head>

<body>
    <div class="header">
        <h1>Fitness Keep - 健身社区</h1>
        <p>记录运动，分享生活，健康每一天</p>
    </div>

    <div class="nav-bar">
        <div class="nav-links">
            <a href="#" class="nav-link active" onclick="showSection('home')">首页</a>
            <a href="#" class="nav-link" onclick="showSection('community')">社区</a>
            <a href="#" class="nav-link" onclick="showSection('diet')">饮食分析</a>
            <a href="#" class="nav-link" onclick="showSection('exercise')">运动记录</a>
            <a href="#" class="nav-link" onclick="showSection('profile')">我的</a>
        </div>
        <div class="user-info" id="userInfo">
            <div class="user-avatar" id="userAvatar">未</div>
            <span id="username">未登录</span>
            <button class="btn btn-primary" onclick="showLoginForm()" id="loginBtn">登录</button>
            <button class="btn btn-secondary" onclick="logout()" id="logoutBtn" style="display: none;">退出</button>
        </div>
    </div>

    <div class="content">
        <!-- 登录注册区域 -->
        <div class="login-section" id="loginSection">
            <h2>用户登录/注册</h2>
            <div class="form-group">
                <label for="loginUsername">用户名:</label>
                <input type="text" id="loginUsername" placeholder="请输入用户名">
            </div>
            <div class="form-group">
                <label for="loginPassword">密码:</label>
                <input type="password" id="loginPassword" placeholder="请输入密码">
            </div>
            <div class="form-group">
                <label for="confirmPassword">确认密码:</label>
                <input type="password" id="confirmPassword" placeholder="请再次输入密码">
            </div>
            <button class="btn btn-primary" onclick="register()">注册</button>
            <button class="btn btn-success" onclick="login()">登录</button>
            <div id="loginResult"></div>
        </div>

        <!-- 首页功能展示 -->
        <div id="homeSection">
            <div class="feature-grid">
                <div class="feature-card">
                    <div class="feature-title">🏃‍♂️ 运动记录</div>
                    <div class="feature-description">
                        记录你的运动数据，包括运动类型、时长、心率等。支持跑步、健身等多种运动类型。
                    </div>
                    <button class="btn btn-primary" onclick="showSection('exercise')">开始运动</button>
                </div>

                <div class="feature-card">
                    <div class="feature-title">🍎 饮食分析</div>
                    <div class="feature-description">
                        记录每日饮食，自动计算热量、蛋白质、碳水化合物、脂肪等营养成分。
                    </div>
                    <button class="btn btn-success" onclick="showSection('diet')">记录饮食</button>
                </div>

                <div class="feature-card">
                    <div class="feature-title">👥 社区分享</div>
                    <div class="feature-description">
                        分享你的运动成果和生活点滴，与志同道合的朋友交流健身心得。
                    </div>
                    <button class="btn btn-info" onclick="showSection('community')">查看社区</button>
                </div>

                <div class="feature-card">
                    <div class="feature-title">👤 个人信息</div>
                    <div class="feature-description">
                        管理你的个人信息，包括身高、体重、性别、生日等基本信息。
                    </div>
                    <button class="btn btn-warning" onclick="showSection('profile')">个人信息</button>
                </div>
            </div>
        </div>

        <!-- 社区页面 -->
        <div id="communitySection" class="hidden">
            <div class="community-header">
                <h2>社区动态</h2>
                <button class="btn btn-primary" onclick="showCreatePostForm()">发布动态</button>
            </div>

            <!-- 发布帖子表单 -->
            <div id="createPostForm" class="hidden">
                <div class="form-card">
                    <h3>发布新动态</h3>
                    <div class="form-group">
                        <label for="postTitle">标题:</label>
                        <input type="text" id="postTitle" placeholder="请输入标题" maxlength="200">
                    </div>
                    <div class="form-group">
                        <label for="postContent">内容:</label>
                        <textarea id="postContent" placeholder="分享你的运动心得和生活点滴..." rows="5"></textarea>
                    </div>
                    <div class="form-actions">
                        <button class="btn btn-primary" onclick="createPost()">发布</button>
                        <button class="btn btn-secondary" onclick="hideCreatePostForm()">取消</button>
                    </div>
                </div>
            </div>

            <!-- 帖子列表 -->
            <div id="postsList">
                <div class="loading">加载中...</div>
            </div>
        </div>

        <!-- 饮食分析页面 -->
        <div id="dietSection" class="hidden">
            <div class="diet-header">
                <h2>饮食热量分析</h2>
                <div class="diet-controls">
                    <input type="date" id="dietDate" onchange="loadDietRecords()">
                    <button class="btn btn-primary" onclick="showAddFoodForm()">添加食物</button>
                </div>
            </div>

            <!-- 营养汇总 -->
            <div id="nutritionSummary" class="nutrition-card">
                <h3>今日营养汇总</h3>
                <div class="nutrition-grid">
                    <div class="nutrition-item">
                        <span class="nutrition-label">总热量</span>
                        <span class="nutrition-value" id="totalCalories">0</span>
                        <span class="nutrition-unit">千卡</span>
                    </div>
                    <div class="nutrition-item">
                        <span class="nutrition-label">碳水化合物</span>
                        <span class="nutrition-value" id="totalCarbs">0</span>
                        <span class="nutrition-unit">克</span>
                    </div>
                    <div class="nutrition-item">
                        <span class="nutrition-label">蛋白质</span>
                        <span class="nutrition-value" id="totalProtein">0</span>
                        <span class="nutrition-unit">克</span>
                    </div>
                    <div class="nutrition-item">
                        <span class="nutrition-label">脂肪</span>
                        <span class="nutrition-value" id="totalFat">0</span>
                        <span class="nutrition-unit">克</span>
                    </div>
                </div>
            </div>

            <!-- 添加食物表单 -->
            <div id="addFoodForm" class="hidden">
                <div class="form-card">
                    <h3>添加食物记录</h3>
                    <div class="form-group">
                        <label for="foodSearch">搜索食物:</label>
                        <input type="text" id="foodSearch" placeholder="输入食物名称搜索..." onkeyup="searchFoods()">
                    </div>
                    <div class="form-group">
                        <label for="foodCategory">食物分类:</label>
                        <select id="foodCategory" onchange="loadFoodsByCategory()">
                            <option value="">全部分类</option>
                        </select>
                    </div>
                    <div id="foodList" class="food-list">
                        <!-- 食物列表将在这里显示 -->
                    </div>
                    <div id="selectedFoodForm" class="hidden">
                        <div class="form-group">
                            <label for="selectedFoodName">已选食物:</label>
                            <input type="text" id="selectedFoodName" readonly>
                            <input type="hidden" id="selectedFoodId">
                        </div>
                        <div class="form-group">
                            <label for="foodAmount">食用量 (克):</label>
                            <input type="number" id="foodAmount" placeholder="请输入食用量" min="1" max="10000">
                        </div>
                        <div class="form-group">
                            <label for="mealType">餐次:</label>
                            <select id="mealType">
                                <option value="早餐">早餐</option>
                                <option value="午餐">午餐</option>
                                <option value="晚餐">晚餐</option>
                                <option value="加餐">加餐</option>
                            </select>
                        </div>
                        <div class="form-actions">
                            <button class="btn btn-primary" onclick="addDietRecord()">添加记录</button>
                            <button class="btn btn-secondary" onclick="cancelAddFood()">取消</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 饮食记录列表 -->
            <div id="dietRecordsList">
                <h3>今日饮食记录</h3>
                <div id="dietRecordsContent">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        </div>

        <!-- 运动记录页面 -->
        <div id="exerciseSection" class="hidden">
            <div class="exercise-header">
                <h2>运动记录</h2>
                <button class="btn btn-primary" onclick="showStartExerciseForm()">开始运动</button>
            </div>

            <!-- 进行中的运动 -->
            <div id="ongoingExercisesContainer">
                <!-- 进行中的运动将在这里动态显示 -->
            </div>

            <!-- 开始运动表单 -->
            <div id="startExerciseForm" class="hidden">
                <div class="form-card">
                    <h3>选择运动</h3>
                    <div class="form-group">
                        <label for="exerciseCategory">运动分类:</label>
                        <select id="exerciseCategory" onchange="loadExercisesByCategory()">
                            <option value="">所有分类</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="exerciseSearch">搜索运动:</label>
                        <input type="text" id="exerciseSearch" placeholder="输入运动名称" oninput="searchExercises()">
                    </div>
                    <div class="exercise-list" id="exerciseList">
                        <!-- 运动列表将在这里动态加载 -->
                    </div>
                    <div class="form-actions">
                        <button class="btn btn-secondary" onclick="cancelStartExercise()">取消</button>
                    </div>
                </div>
            </div>

            <!-- 运动记录列表 -->
            <div class="exercise-records">
                <h3>运动记录</h3>
                <div class="records-filter">
                    <select id="recordFilter" onchange="filterRecords()">
                        <option value="all">全部记录</option>
                        <option value="completed">已完成</option>
                        <option value="ongoing">进行中</option>
                    </select>
                </div>
                <div id="exerciseRecordsList" class="records-list">
                    <!-- 运动记录将在这里动态加载 -->
                </div>
            </div>
        </div>

        <!-- 个人信息页面 -->
        <div id="profileSection" class="hidden">
            <div class="profile-header">
                <h2>个人信息</h2>
                <button class="btn btn-primary" onclick="showEditProfileForm()">编辑信息</button>
            </div>

            <!-- 个人信息显示 -->
            <div id="profileDisplay" class="profile-card">
                <div class="profile-info">
                    <div class="info-row">
                        <span class="info-label">用户名:</span>
                        <span class="info-value" id="profileUsername">-</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">身高:</span>
                        <span class="info-value" id="profileHeight">-</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">体重:</span>
                        <span class="info-value" id="profileWeight">-</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">性别:</span>
                        <span class="info-value" id="profileGender">-</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">生日:</span>
                        <span class="info-value" id="profileBirthday">-</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">个人签名:</span>
                        <span class="info-value" id="profileDes">-</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">所在地:</span>
                        <span class="info-value" id="profileLocation">-</span>
                    </div>
                </div>
            </div>

            <!-- 编辑个人信息表单 -->
            <div id="editProfileForm" class="hidden">
                <div class="form-card">
                    <h3>编辑个人信息</h3>

                    <div class="form-group">
                        <label for="editName">用户名:</label>
                        <input type="text" id="editName" placeholder="请输入用户名">
                    </div>

                    <div class="form-group">
                        <label for="editHeight">身高 (cm):</label>
                        <input type="number" id="editHeight" placeholder="请输入身高" min="100" max="250" step="0.1">
                    </div>
                    <div class="form-group">
                        <label for="editWeight">体重 (kg):</label>
                        <input type="number" id="editWeight" placeholder="请输入体重" min="20" max="300" step="0.1">
                    </div>
                    <div class="form-group">
                        <label for="editGender">性别:</label>
                        <select id="editGender">
                            <option value="">请选择性别</option>
                            <option value="male">男</option>
                            <option value="female">女</option>
                            <option value="other">其他</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="editBirthday">生日:</label>
                        <input type="date" id="editBirthday">
                    </div>
                    <div class="form-group">
                        <label for="editDes">个人签名:</label>
                        <textarea id="editDes" placeholder="请输入个人签名" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="editLocation">所在地:</label>
                        <input type="text" id="editLocation" placeholder="请输入所在地">
                    </div>
                    <div class="form-actions">
                        <button class="btn btn-primary" onclick="saveProfile()">保存</button>
                        <button class="btn btn-secondary" onclick="cancelEditProfile()">取消</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentUser = null;

        // 显示不同页面区域
        function showSection(sectionName) {
            // 隐藏所有区域
            document.getElementById('homeSection').classList.add('hidden');
            document.getElementById('communitySection').classList.add('hidden');
            document.getElementById('dietSection').classList.add('hidden');
            document.getElementById('exerciseSection').classList.add('hidden');
            document.getElementById('profileSection').classList.add('hidden');

            // 移除所有导航链接的active类
            document.querySelectorAll('.nav-link').forEach(link => {
                link.classList.remove('active');
            });

            // 显示指定区域
            document.getElementById(sectionName + 'Section').classList.remove('hidden');

            // 添加active类到当前导航链接
            event.target.classList.add('active');

            // 根据页面加载相应数据
            if (sectionName === 'exercise') {
                loadExerciseData();
            }
        }

        // 显示登录表单
        function showLoginForm() {
            document.getElementById('loginSection').style.display = 'block';
        }

        // 隐藏登录表单
        function hideLoginForm() {
            document.getElementById('loginSection').style.display = 'none';
        }

        // 用户注册
        function register() {
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            if (!username || !password || !confirmPassword) {
                showResult('请填写完整信息', 'error');
                return;
            }

            if (password !== confirmPassword) {
                showResult('两次输入的密码不一致', 'error');
                return;
            }

            fetch('/api/user/signUp', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: username,
                    password: password,
                    confirmPassword: confirmPassword
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showResult('注册成功！', 'success');
                        currentUser = data.user;
                        updateUserInfo();
                    } else {
                        showResult('注册失败：' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showResult('注册失败：' + error.message, 'error');
                });
        }

        // 用户登录
        function login() {
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;

            if (!username || !password) {
                showResult('请填写用户名和密码', 'error');
                return;
            }

            fetch('/api/user/signIn', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showResult('登录成功！', 'success');
                        currentUser = data.user;
                        // 保存用户信息到localStorage
                        localStorage.setItem('currentUser', JSON.stringify(data.user));
                        updateUserInfo();
                        hideLoginForm();
                    } else {
                        showResult('登录失败：' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showResult('登录失败：' + error.message, 'error');
                });
        }

        // 显示结果信息
        function showResult(message, type) {
            const resultDiv = document.getElementById('loginResult');
            resultDiv.textContent = message;
            resultDiv.className = 'result ' + type;
        }

        // 退出登录
        function logout() {
            currentUser = null;
            localStorage.removeItem('currentUser');
            updateUserInfo();
            showResult('已退出登录', 'success');
            // 如果当前在需要登录的页面，跳转到首页
            const currentSection = document.querySelector('.section:not(.hidden)');
            if (currentSection && currentSection.id !== 'homeSection') {
                showSection('home');
            }
        }

        // 更新用户信息显示
        function updateUserInfo() {
            if (currentUser) {
                document.getElementById('username').textContent = currentUser.username;
                document.getElementById('userAvatar').textContent = currentUser.username.charAt(0).toUpperCase();
                document.getElementById('userAvatar').style.display = 'flex';
                document.getElementById('loginBtn').style.display = 'none';
                document.getElementById('logoutBtn').style.display = 'inline-block';

                // 如果当前在运动页面，重新加载运动数据
                if (!document.getElementById('exerciseSection').classList.contains('hidden')) {
                    loadExerciseData();
                }
            } else {
                document.getElementById('username').textContent = '未登录';
                document.getElementById('userAvatar').style.display = 'none';
                document.getElementById('loginBtn').style.display = 'inline-block';
                document.getElementById('logoutBtn').style.display = 'none';
            }
        }

        // 页面加载完成后的初始化
        window.onload = function () {
            // 从localStorage恢复用户登录状态
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                try {
                    currentUser = JSON.parse(savedUser);
                } catch (e) {
                    console.error('解析用户信息失败:', e);
                    localStorage.removeItem('currentUser');
                }
            }
            updateUserInfo();

            // 如果用户已登录，检查是否有进行中的运动
            if (currentUser) {
                checkCurrentExercise();
            }
        };

        // 社区功能相关函数
        function showCreatePostForm() {
            if (!currentUser) {
                alert('请先登录');
                return;
            }
            document.getElementById('createPostForm').classList.remove('hidden');
        }

        function hideCreatePostForm() {
            document.getElementById('createPostForm').classList.add('hidden');
            document.getElementById('postTitle').value = '';
            document.getElementById('postContent').value = '';
        }

        function createPost() {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            const title = document.getElementById('postTitle').value.trim();
            const content = document.getElementById('postContent').value.trim();

            if (!title || !content) {
                alert('请填写标题和内容');
                return;
            }

            fetch('/api/community-posts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    userId: currentUser.id,
                    title: title,
                    content: content
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('发布成功！');
                        hideCreatePostForm();
                        loadPosts();
                    } else {
                        alert('发布失败：' + data.message);
                    }
                })
                .catch(error => {
                    alert('发布失败：' + error.message);
                });
        }

        function loadPosts() {
            const postsList = document.getElementById('postsList');
            postsList.innerHTML = '<div class="loading">加载中...</div>';

            // 构建请求URL，包含当前用户ID
            let url = '/api/community-posts';
            if (currentUser) {
                url += `?currentUserId=${currentUser.id}`;
            }

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayPosts(data.data);
                    } else {
                        postsList.innerHTML = '<div class="error">加载失败：' + data.message + '</div>';
                    }
                })
                .catch(error => {
                    postsList.innerHTML = '<div class="error">加载失败：' + error.message + '</div>';
                });
        }

        function displayPosts(posts) {
            const postsList = document.getElementById('postsList');

            if (posts.length === 0) {
                postsList.innerHTML = '<div class="loading">暂无动态，快来发布第一条吧！</div>';
                return;
            }

            postsList.innerHTML = posts.map(post => `
                <div class="post-card">
                    <div class="post-author">
                        <div class="user-avatar">${post.userId}</div>
                        <div>
                            <div class="post-title">${post.title}</div>
                            <div class="post-meta">${formatDate(post.createdAt)}</div>
                        </div>
                    </div>
                    <div class="post-content">${post.content}</div>
                    <div class="post-stats">
                        <span class="stat-item">
                            <i class="stat-icon">💬</i>
                            <span class="stat-count">${post.commentCount || 0}</span>
                        </span>
                    </div>
                    <div class="post-actions" data-post-id="${post.id}">
                        <button class="action-btn ${post.isLiked ? 'liked' : ''}" onclick="togglePostLike(${post.id})">
                            <i class="action-icon">${post.isLiked ? '❤️' : '🤍'}</i>
                            <span class="action-text">${post.isLiked ? '取消点赞' : '点赞'}</span>
                            <span class="action-count">${post.likeCount || 0}</span>
                        </button>
                        <button class="action-btn ${post.isFavorited ? 'favorited' : ''}" onclick="togglePostFavorite(${post.id})">
                            <i class="action-icon">${post.isFavorited ? '⭐' : '☆'}</i>
                            <span class="action-text">${post.isFavorited ? '取消收藏' : '收藏'}</span>
                            <span class="action-count">${post.favoriteCount || 0}</span>
                        </button>
                        <button class="action-btn" onclick="showComments(${post.id})">评论</button>
                        <button class="action-btn" onclick="loadComments(${post.id})">查看评论</button>
                    </div>
                    <div id="comments-${post.id}" class="comments-section hidden"></div>
                </div>
            `).join('');
        }

        function showComments(postId) {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            const commentsSection = document.getElementById(`comments-${postId}`);
            commentsSection.classList.remove('hidden');

            // 显示评论输入框
            const commentForm = document.createElement('div');
            commentForm.className = 'comment-form';
            commentForm.innerHTML = `
                <textarea class="comment-input" placeholder="写下你的评论..." id="comment-${postId}"></textarea>
                <button class="btn btn-primary" onclick="addComment(${postId})">发表评论</button>
            `;
            commentsSection.appendChild(commentForm);
        }

        function addComment(postId) {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            const content = document.getElementById(`comment-${postId}`).value.trim();
            if (!content) {
                alert('请输入评论内容');
                return;
            }

            fetch('/api/post-comments', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    postId: postId,
                    userId: currentUser.id,
                    content: content
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById(`comment-${postId}`).value = '';
                        loadComments(postId);
                    } else {
                        alert('评论失败：' + data.message);
                    }
                })
                .catch(error => {
                    alert('评论失败：' + error.message);
                });
        }

        function loadComments(postId) {
            const commentsSection = document.getElementById(`comments-${postId}`);

            // 显示评论区域
            commentsSection.classList.remove('hidden');

            // 构建请求URL，包含当前用户ID
            let url = `/api/post-comments/post/${postId}`;
            if (currentUser) {
                url += `?currentUserId=${currentUser.id}`;
            }

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayComments(postId, data.data);
                    } else {
                        commentsSection.innerHTML = '<div class="error">加载评论失败：' + data.message + '</div>';
                    }
                })
                .catch(error => {
                    commentsSection.innerHTML = '<div class="error">加载评论失败：' + error.message + '</div>';
                });
        }

        function displayComments(postId, comments) {
            const commentsSection = document.getElementById(`comments-${postId}`);

            if (comments.length === 0) {
                commentsSection.innerHTML = '<div class="comment">暂无评论</div>';
                return;
            }

            const commentsHtml = comments.map(comment => `
                <div class="comment">
                    <div class="comment-header">
                        <span class="comment-author">用户${comment.userId}</span>
                        <span class="comment-time">${formatDate(comment.createdAt)}</span>
                    </div>
                    <div class="comment-content">${comment.content}</div>
                    <div class="comment-actions">
                        <button class="action-btn ${comment.isLiked ? 'liked' : ''}" onclick="toggleCommentLike(${comment.id})">
                            <i class="action-icon">${comment.isLiked ? '❤️' : '🤍'}</i>
                            <span class="action-text">${comment.isLiked ? '取消点赞' : '点赞'}</span>
                            <span class="action-count">${comment.likeCount || 0}</span>
                        </button>
                    </div>
                </div>
            `).join('');

            // 保留评论输入框
            const commentForm = commentsSection.querySelector('.comment-form');
            commentsSection.innerHTML = commentsHtml;
            if (commentForm) {
                commentsSection.appendChild(commentForm);
            }
        }

        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 帖子点赞功能
        function togglePostLike(postId) {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            // 防重复点击
            const likeButton = document.querySelector(`[onclick="togglePostLike(${postId})"]`);
            if (likeButton && likeButton.disabled) {
                return;
            }
            if (likeButton) {
                likeButton.disabled = true;
            }

            fetch('/api/post-like/toggle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `userId=${currentUser.id}&postId=${postId}`
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 直接更新当前帖子的状态，而不是重新加载所有帖子
                        updatePostLikeStatus(postId, data);
                    } else {
                        alert('操作失败：' + data.message);
                    }
                })
                .catch(error => {
                    alert('操作失败：' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    if (likeButton) {
                        likeButton.disabled = false;
                    }
                });
        }

        // 更新帖子点赞状态
        function updatePostLikeStatus(postId, likeData) {
            const postCard = document.querySelector(`[data-post-id="${postId}"]`).closest('.post-card');
            if (!postCard) return;

            const likeButton = postCard.querySelector(`[onclick="togglePostLike(${postId})"]`);
            if (!likeButton) return;

            const likeCountSpan = likeButton.querySelector('.action-count');
            const likeIcon = likeButton.querySelector('.action-icon');
            const likeText = likeButton.querySelector('.action-text');

            if (!likeCountSpan || !likeIcon || !likeText) return;

            if (likeData && likeData.isLiked !== undefined) {
                // 更新点赞状态
                if (likeData.isLiked) {
                    likeButton.classList.add('liked');
                    likeIcon.textContent = '❤️';
                    likeText.textContent = '取消点赞';
                } else {
                    likeButton.classList.remove('liked');
                    likeIcon.textContent = '🤍';
                    likeText.textContent = '点赞';
                }
            }

            // 更新点赞数量
            if (likeData && likeData.likeCount !== undefined) {
                likeCountSpan.textContent = likeData.likeCount;
            }
        }

        // 帖子收藏功能
        function togglePostFavorite(postId) {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            // 防重复点击
            const favoriteButton = document.querySelector(`[onclick="togglePostFavorite(${postId})"]`);
            if (favoriteButton && favoriteButton.disabled) {
                return;
            }
            if (favoriteButton) {
                favoriteButton.disabled = true;
            }

            fetch('/api/post-favorite/toggle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `userId=${currentUser.id}&postId=${postId}`
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 直接更新当前帖子的状态
                        updatePostFavoriteStatus(postId, data);
                    } else {
                        alert('操作失败：' + data.message);
                    }
                })
                .catch(error => {
                    alert('操作失败：' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    if (favoriteButton) {
                        favoriteButton.disabled = false;
                    }
                });
        }

        // 更新帖子收藏状态
        function updatePostFavoriteStatus(postId, favoriteData) {
            const postCard = document.querySelector(`[data-post-id="${postId}"]`).closest('.post-card');
            if (!postCard) return;

            const favoriteButton = postCard.querySelector(`[onclick="togglePostFavorite(${postId})"]`);
            if (!favoriteButton) return;

            const favoriteCountSpan = favoriteButton.querySelector('.action-count');
            const favoriteIcon = favoriteButton.querySelector('.action-icon');
            const favoriteText = favoriteButton.querySelector('.action-text');

            if (!favoriteCountSpan || !favoriteIcon || !favoriteText) return;

            if (favoriteData && favoriteData.isFavorited !== undefined) {
                // 更新收藏状态
                if (favoriteData.isFavorited) {
                    favoriteButton.classList.add('favorited');
                    favoriteIcon.textContent = '⭐';
                    favoriteText.textContent = '取消收藏';
                } else {
                    favoriteButton.classList.remove('favorited');
                    favoriteIcon.textContent = '☆';
                    favoriteText.textContent = '收藏';
                }
            }

            // 更新收藏数量
            if (favoriteData && favoriteData.favoriteCount !== undefined) {
                favoriteCountSpan.textContent = favoriteData.favoriteCount;
            }
        }

        // 评论点赞功能
        function toggleCommentLike(commentId) {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            // 防重复点击
            const commentLikeButton = document.querySelector(`[onclick="toggleCommentLike(${commentId})"]`);
            if (commentLikeButton && commentLikeButton.disabled) {
                return;
            }
            if (commentLikeButton) {
                commentLikeButton.disabled = true;
            }

            fetch('/api/comment-like/toggle', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `userId=${currentUser.id}&commentId=${commentId}`
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 直接更新当前评论的状态
                        updateCommentLikeStatus(commentId, data);
                    } else {
                        alert('操作失败：' + data.message);
                    }
                })
                .catch(error => {
                    alert('操作失败：' + error.message);
                })
                .finally(() => {
                    // 恢复按钮状态
                    if (commentLikeButton) {
                        commentLikeButton.disabled = false;
                    }
                });
        }

        // 更新评论点赞状态
        function updateCommentLikeStatus(commentId, likeData) {
            const commentElement = document.querySelector(`[onclick="toggleCommentLike(${commentId})"]`);
            if (!commentElement) return;

            const likeCountSpan = commentElement.querySelector('.action-count');
            const likeIcon = commentElement.querySelector('.action-icon');
            const likeText = commentElement.querySelector('.action-text');

            if (!likeCountSpan || !likeIcon || !likeText) return;

            if (likeData && likeData.isLiked !== undefined) {
                // 更新点赞状态
                if (likeData.isLiked) {
                    commentElement.classList.add('liked');
                    likeIcon.textContent = '❤️';
                    likeText.textContent = '取消点赞';
                } else {
                    commentElement.classList.remove('liked');
                    likeIcon.textContent = '🤍';
                    likeText.textContent = '点赞';
                }
            }

            // 更新点赞数量
            if (likeData && likeData.likeCount !== undefined) {
                likeCountSpan.textContent = likeData.likeCount;
            }
        }

        // 修改showSection函数，在显示社区页面时加载帖子
        function showSection(sectionName) {
            // 隐藏所有区域
            document.getElementById('homeSection').classList.add('hidden');
            document.getElementById('communitySection').classList.add('hidden');
            document.getElementById('dietSection').classList.add('hidden');
            document.getElementById('exerciseSection').classList.add('hidden');
            document.getElementById('profileSection').classList.add('hidden');

            // 移除所有导航链接的active类
            document.querySelectorAll('.nav-link').forEach(link => {
                link.classList.remove('active');
            });

            // 显示指定区域
            document.getElementById(sectionName + 'Section').classList.remove('hidden');

            // 添加active类到当前导航链接
            event.target.classList.add('active');

            // 如果是社区页面，加载帖子
            if (sectionName === 'community') {
                loadPosts();
            }

            // 如果是个人信息页面，加载个人信息
            if (sectionName === 'profile') {
                loadUserProfile();
            }

            // 如果是饮食分析页面，加载饮食数据
            if (sectionName === 'diet') {
                loadDietData();
            }

            // 如果是运动页面，加载运动数据
            if (sectionName === 'exercise') {
                loadExerciseData();
            }
        }

        // 个人信息功能相关函数
        function loadUserProfile() {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            // 显示用户名
            document.getElementById('profileUsername').textContent = currentUser.username;

            // 加载用户详细信息
            fetch(`/api/user-profile/${currentUser.id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data) {
                        displayUserProfile(data.data);
                    } else {
                        // 如果没有个人信息，显示默认值
                        displayUserProfile(null);
                    }
                })
                .catch(error => {
                    console.error('加载个人信息失败:', error);
                    displayUserProfile(null);
                });
        }

        function displayUserProfile(profile) {
            if (profile) {
                document.getElementById('profileUsername').textContent = profile.name || currentUser?.username || '-';
                document.getElementById('profileHeight').textContent = profile.height ? `${profile.height} cm` : '-';
                document.getElementById('profileWeight').textContent = profile.weight ? `${profile.weight} kg` : '-';
                document.getElementById('profileGender').textContent = getGenderText(profile.gender);
                document.getElementById('profileBirthday').textContent = profile.birthday ? formatBirthday(profile.birthday) : '-';
                document.getElementById('profileDes').textContent = profile.des || '-';
                document.getElementById('profileLocation').textContent = profile.location || '-';
            } else {
                document.getElementById('profileUsername').textContent = currentUser?.username || '-';
                document.getElementById('profileHeight').textContent = '-';
                document.getElementById('profileWeight').textContent = '-';
                document.getElementById('profileGender').textContent = '-';
                document.getElementById('profileBirthday').textContent = '-';
                document.getElementById('profileDes').textContent = '-';
                document.getElementById('profileLocation').textContent = '-';
            }
        }

        function showEditProfileForm() {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            // 隐藏显示区域，显示编辑表单
            document.getElementById('profileDisplay').classList.add('hidden');
            document.getElementById('editProfileForm').classList.remove('hidden');

            // 加载当前个人信息到表单
            fetch(`/api/user-profile/${currentUser.id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data) {
                        const profile = data.data;
                        document.getElementById('editName').value = profile.name || currentUser?.username || '';
                        document.getElementById('editHeight').value = profile.height || '';
                        document.getElementById('editWeight').value = profile.weight || '';
                        document.getElementById('editGender').value = profile.gender || '';
                        document.getElementById('editBirthday').value = profile.birthday || '';
                        document.getElementById('editDes').value = profile.des || '';
                        document.getElementById('editLocation').value = profile.location || '';
                    } else {
                        // 清空表单
                        document.getElementById('editName').value = currentUser?.username || '';
                        document.getElementById('editHeight').value = '';
                        document.getElementById('editWeight').value = '';
                        document.getElementById('editGender').value = '';
                        document.getElementById('editBirthday').value = '';
                        document.getElementById('editDes').value = '';
                        document.getElementById('editLocation').value = '';
                    }
                })
                .catch(error => {
                    console.error('加载个人信息失败:', error);
                    // 清空表单
                    document.getElementById('editName').value = currentUser?.username || '';
                    document.getElementById('editHeight').value = '';
                    document.getElementById('editWeight').value = '';
                    document.getElementById('editGender').value = '';
                    document.getElementById('editBirthday').value = '';
                    document.getElementById('editDes').value = '';
                    document.getElementById('editLocation').value = '';
                });
        }

        function cancelEditProfile() {
            // 隐藏编辑表单，显示个人信息
            document.getElementById('editProfileForm').classList.add('hidden');
            document.getElementById('profileDisplay').classList.remove('hidden');

            // 清空编辑表单
            document.getElementById('editName').value = '';
            document.getElementById('editHeight').value = '';
            document.getElementById('editWeight').value = '';
            document.getElementById('editGender').value = '';
            document.getElementById('editBirthday').value = '';
            document.getElementById('editDes').value = '';
            document.getElementById('editLocation').value = '';
        }

        function saveProfile() {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            const name = document.getElementById('editName').value.trim();
            const height = document.getElementById('editHeight').value;
            const weight = document.getElementById('editWeight').value;
            const gender = document.getElementById('editGender').value;
            const birthday = document.getElementById('editBirthday').value;
            const des = document.getElementById('editDes').value.trim();
            const location = document.getElementById('editLocation').value.trim();

            // 验证数据
            if (!name) {
                alert('用户名不能为空');
                return;
            }
            if (height && (height < 100 || height > 250)) {
                alert('身高必须在100-250cm之间');
                return;
            }
            if (weight && (weight < 20 || weight > 300)) {
                alert('体重必须在20-300kg之间');
                return;
            }

            const profileData = {
                userId: currentUser.id,
                name: name,
                height: height ? parseFloat(height) : null,
                weight: weight ? parseFloat(weight) : null,
                gender: gender || null,
                birthday: birthday || null,
                des: des || null,
                location: location || null
            };

            fetch('/api/user-profile/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(profileData)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('个人信息保存成功！');
                        cancelEditProfile();
                        loadUserProfile(); // 重新加载个人信息
                    } else {
                        alert('保存失败：' + data.message);
                    }
                })
                .catch(error => {
                    alert('保存失败：' + error.message);
                });
        }

        function getGenderText(gender) {
            switch (gender) {
                case 'male': return '男';
                case 'female': return '女';
                case 'other': return '其他';
                default: return '-';
            }
        }

        function formatBirthday(birthday) {
            if (!birthday) return '-';
            const date = new Date(birthday);
            return date.toLocaleDateString('zh-CN');
        }

        // 饮食分析功能相关函数
        function loadDietData() {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            // 设置当前日期
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('dietDate').value = today;

            // 加载食物分类
            loadFoodCategories();

            // 加载饮食记录
            loadDietRecords();
        }

        function loadFoodCategories() {
            fetch('/api/food-info/categories')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const categorySelect = document.getElementById('foodCategory');
                        categorySelect.innerHTML = '<option value="">全部分类</option>';
                        data.data.forEach(category => {
                            categorySelect.innerHTML += `<option value="${category}">${category}</option>`;
                        });
                    }
                })
                .catch(error => {
                    console.error('加载食物分类失败:', error);
                });
        }

        function loadFoodsByCategory() {
            const category = document.getElementById('foodCategory').value;
            const foodList = document.getElementById('foodList');

            if (!category) {
                loadAllFoods();
                return;
            }

            fetch(`/api/food-info/category/${encodeURIComponent(category)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayFoodList(data.data);
                    }
                })
                .catch(error => {
                    console.error('加载分类食物失败:', error);
                });
        }

        function loadAllFoods() {
            fetch('/api/food-info')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayFoodList(data.data);
                    }
                })
                .catch(error => {
                    console.error('加载食物列表失败:', error);
                });
        }

        function searchFoods() {
            const keyword = document.getElementById('foodSearch').value.trim();
            if (!keyword) {
                loadAllFoods();
                return;
            }

            fetch(`/api/food-info/search?keyword=${encodeURIComponent(keyword)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayFoodList(data.data);
                    }
                })
                .catch(error => {
                    console.error('搜索食物失败:', error);
                });
        }

        function displayFoodList(foods) {
            const foodList = document.getElementById('foodList');

            if (foods.length === 0) {
                foodList.innerHTML = '<div class="food-item">暂无食物数据</div>';
                return;
            }

            foodList.innerHTML = foods.map(food => `
                <div class="food-item" onclick="selectFood(${food.id}, '${food.name}')">
                    <div class="food-item-name">${food.name}</div>
                    <div class="food-item-nutrition">
                        热量: ${food.calories}千卡 | 碳水: ${food.carbohydrates}g | 蛋白质: ${food.protein}g | 脂肪: ${food.fat}g
                    </div>
                </div>
            `).join('');
        }

        function selectFood(foodId, foodName) {
            document.getElementById('selectedFoodId').value = foodId;
            document.getElementById('selectedFoodName').value = foodName;
            document.getElementById('selectedFoodForm').classList.remove('hidden');

            // 高亮选中的食物
            document.querySelectorAll('.food-item').forEach(item => {
                item.classList.remove('selected');
            });
            event.target.closest('.food-item').classList.add('selected');
        }

        function showAddFoodForm() {
            if (!currentUser) {
                alert('请先登录');
                return;
            }
            document.getElementById('addFoodForm').classList.remove('hidden');
            loadAllFoods();
        }

        function cancelAddFood() {
            document.getElementById('addFoodForm').classList.add('hidden');
            document.getElementById('selectedFoodForm').classList.add('hidden');
            document.getElementById('foodSearch').value = '';
            document.getElementById('foodAmount').value = '';
            document.getElementById('selectedFoodId').value = '';
            document.getElementById('selectedFoodName').value = '';
        }

        function addDietRecord() {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            const foodId = document.getElementById('selectedFoodId').value;
            const amount = document.getElementById('foodAmount').value;
            const mealType = document.getElementById('mealType').value;
            const date = document.getElementById('dietDate').value;

            if (!foodId || !amount || !mealType) {
                alert('请填写完整信息');
                return;
            }

            if (amount <= 0 || amount > 10000) {
                alert('食用量必须在1-10000克之间');
                return;
            }

            // 验证日期格式
            if (!date) {
                alert('请选择日期');
                return;
            }

            console.log('发送的饮食记录数据:', {
                userId: currentUser.id,
                foodId: parseInt(foodId),
                amount: parseFloat(amount),
                mealTime: date + 'T12:00:00',
                mealType: mealType
            });

            const dietRecord = {
                userId: currentUser.id,
                foodId: parseInt(foodId),
                amount: parseFloat(amount),
                mealTime: date + 'T12:00:00',
                mealType: mealType
            };

            fetch('/api/diet-records', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(dietRecord)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('饮食记录添加成功！');
                        cancelAddFood();
                        loadDietRecords();
                    } else {
                        alert('添加失败：' + data.message);
                    }
                })
                .catch(error => {
                    alert('添加失败：' + error.message);
                });
        }

        function loadDietRecords() {
            if (!currentUser) {
                return;
            }

            const date = document.getElementById('dietDate').value;
            if (!date) {
                return;
            }

            // 加载营养汇总
            fetch(`/api/diet-records/user/${currentUser.id}/summary/${date}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data) {
                        displayNutritionSummary(data.data);
                    } else {
                        displayNutritionSummary(null);
                    }
                })
                .catch(error => {
                    console.error('加载营养汇总失败:', error);
                    displayNutritionSummary(null);
                });

            // 加载饮食记录
            fetch(`/api/diet-records/user/${currentUser.id}/date/${date}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayDietRecords(data.data);
                    } else {
                        document.getElementById('dietRecordsContent').innerHTML = '<div class="error">加载失败：' + data.message + '</div>';
                    }
                })
                .catch(error => {
                    document.getElementById('dietRecordsContent').innerHTML = '<div class="error">加载失败：' + error.message + '</div>';
                });
        }

        function displayNutritionSummary(summary) {
            if (summary) {
                document.getElementById('totalCalories').textContent = summary.totalCalories ? summary.totalCalories.toFixed(1) : '0';
                document.getElementById('totalCarbs').textContent = summary.totalCarbohydrates ? summary.totalCarbohydrates.toFixed(1) : '0';
                document.getElementById('totalProtein').textContent = summary.totalProtein ? summary.totalProtein.toFixed(1) : '0';
                document.getElementById('totalFat').textContent = summary.totalFat ? summary.totalFat.toFixed(1) : '0';
            } else {
                document.getElementById('totalCalories').textContent = '0';
                document.getElementById('totalCarbs').textContent = '0';
                document.getElementById('totalProtein').textContent = '0';
                document.getElementById('totalFat').textContent = '0';
            }
        }

        function displayDietRecords(records) {
            const content = document.getElementById('dietRecordsContent');

            if (records.length === 0) {
                content.innerHTML = '<div class="loading">今日暂无饮食记录</div>';
                return;
            }

            content.innerHTML = records.map(record => `
                <div class="diet-record-item">
                    <div class="diet-record-header">
                        <span class="diet-record-food">${record.foodName || '未知食物'}</span>
                        <span class="diet-record-meal">${record.mealType}</span>
                    </div>
                    <div class="diet-record-nutrition">
                        <span>食用量: ${record.amount}g</span>
                        <span>热量: ${record.totalCalories.toFixed(1)}千卡</span>
                        <span>碳水: ${record.totalCarbohydrates.toFixed(1)}g</span>
                        <span>蛋白质: ${record.totalProtein.toFixed(1)}g</span>
                    </div>
                </div>
            `).join('');
        }

        // 运动记录功能相关函数

        function loadExerciseData() {
            if (!currentUser) {
                // 如果未登录，只加载运动分类，不加载用户数据
                loadExerciseCategories();
                return;
            }

            // 加载运动分类
            loadExerciseCategories();

            // 加载运动记录
            loadExerciseRecords();

            // 检查是否有进行中的运动
            checkCurrentExercise();
        }

        function loadExerciseCategories() {
            fetch('/api/exercise-info/categories')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const categorySelect = document.getElementById('exerciseCategory');
                        categorySelect.innerHTML = '<option value="">所有分类</option>';
                        data.data.forEach(category => {
                            categorySelect.innerHTML += `<option value="${category}">${category}</option>`;
                        });
                    }
                })
                .catch(error => {
                    console.error('加载运动分类失败:', error);
                });
        }

        function loadExercisesByCategory() {
            const category = document.getElementById('exerciseCategory').value;
            const exerciseList = document.getElementById('exerciseList');

            if (!category) {
                loadAllExercises();
                return;
            }

            fetch(`/api/exercise-info/category/${encodeURIComponent(category)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayExerciseList(data.data);
                    }
                })
                .catch(error => {
                    console.error('加载分类运动失败:', error);
                });
        }

        function loadAllExercises() {
            fetch('/api/exercise-info')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayExerciseList(data.data);
                    }
                })
                .catch(error => {
                    console.error('加载运动列表失败:', error);
                });
        }

        function searchExercises() {
            const keyword = document.getElementById('exerciseSearch').value.trim();
            if (!keyword) {
                loadAllExercises();
                return;
            }

            fetch(`/api/exercise-info/search?keyword=${encodeURIComponent(keyword)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayExerciseList(data.data);
                    }
                })
                .catch(error => {
                    console.error('搜索运动失败:', error);
                });
        }

        function displayExerciseList(exercises) {
            const exerciseList = document.getElementById('exerciseList');

            if (exercises.length === 0) {
                exerciseList.innerHTML = '<div class="exercise-item">暂无运动数据</div>';
                return;
            }

            exerciseList.innerHTML = exercises.map(exercise => `
                <div class="exercise-item" onclick="selectExercise(${exercise.id}, '${exercise.name}')">
                    <div class="exercise-item-name">${exercise.name}</div>
                    <div class="exercise-item-category">${exercise.category}</div>
                    <div class="exercise-item-description">${exercise.description || ''}</div>
                </div>
            `).join('');
        }

        function selectExercise(exerciseId, exerciseName) {
            // 移除之前的选中状态
            document.querySelectorAll('.exercise-item').forEach(item => {
                item.classList.remove('selected');
            });

            // 添加选中状态
            event.target.closest('.exercise-item').classList.add('selected');

            // 开始运动
            startExercise(exerciseId, exerciseName);
        }

        function startExercise(exerciseId, exerciseName) {
            if (!currentUser) {
                alert('请先登录');
                return;
            }

            // 检查是否已有进行中的运动
            fetch(`/api/exercise-records/user/${currentUser.id}/status/进行中`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data.length > 0) {
                        alert('请先结束当前运动');
                        return;
                    }

                    // 没有进行中的运动，可以开始新运动
                    const exerciseData = {
                        userId: currentUser.id,
                        exerciseId: exerciseId
                    };

                    fetch('/api/exercise-records/start', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(exerciseData)
                    })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // 隐藏开始运动表单
                                document.getElementById('startExerciseForm').classList.add('hidden');

                                // 重新检查进行中的运动
                                checkCurrentExercise();

                                alert('运动开始成功！');
                            } else {
                                alert('开始运动失败：' + data.message);
                            }
                        })
                        .catch(error => {
                            console.error('开始运动失败:', error);
                            alert('开始运动失败，请重试');
                        });
                })
                .catch(error => {
                    console.error('检查进行中运动失败:', error);
                    alert('检查运动状态失败，请重试');
                });
        }



        function showStartExerciseForm() {
            document.getElementById('startExerciseForm').classList.remove('hidden');
            loadAllExercises();
        }

        function cancelStartExercise() {
            document.getElementById('startExerciseForm').classList.add('hidden');
            // 清除选中状态
            document.querySelectorAll('.exercise-item').forEach(item => {
                item.classList.remove('selected');
            });
        }

        function loadExerciseRecords() {
            if (!currentUser) {
                // 如果未登录，显示提示信息
                const content = document.getElementById('exerciseRecordsList');
                content.innerHTML = '<p>请先登录查看运动记录</p>';
                return;
            }

            // 确保筛选器设置为"全部记录"
            const recordFilter = document.getElementById('recordFilter');
            if (recordFilter) {
                recordFilter.value = 'all';
            }

            fetch(`/api/exercise-records/user/${currentUser.id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayExerciseRecords(data.data);
                    } else {
                        const content = document.getElementById('exerciseRecordsList');
                        content.innerHTML = '<p>加载运动记录失败</p>';
                    }
                })
                .catch(error => {
                    console.error('加载运动记录失败:', error);
                    const content = document.getElementById('exerciseRecordsList');
                    content.innerHTML = '<p>加载运动记录失败</p>';
                });
        }

        function filterRecords() {
            const filter = document.getElementById('recordFilter').value;
            if (!currentUser) {
                // 如果未登录，显示提示信息
                const content = document.getElementById('exerciseRecordsList');
                content.innerHTML = '<p>请先登录查看运动记录</p>';
                return;
            }

            let url = `/api/exercise-records/user/${currentUser.id}`;
            if (filter === 'completed') {
                url = `/api/exercise-records/user/${currentUser.id}/status/已完成`;
            } else if (filter === 'ongoing') {
                url = `/api/exercise-records/user/${currentUser.id}/status/进行中`;
            }

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayExerciseRecords(data.data);
                    } else {
                        const content = document.getElementById('exerciseRecordsList');
                        content.innerHTML = '<p>筛选运动记录失败</p>';
                    }
                })
                .catch(error => {
                    console.error('筛选运动记录失败:', error);
                    const content = document.getElementById('exerciseRecordsList');
                    content.innerHTML = '<p>筛选运动记录失败</p>';
                });
        }

        function displayExerciseRecords(records) {
            const content = document.getElementById('exerciseRecordsList');

            if (records.length === 0) {
                content.innerHTML = '<p>暂无运动记录</p>';
                return;
            }

            content.innerHTML = records.map(record => {
                const startTime = new Date(record.startTime).toLocaleString();
                const endTime = record.endTime ? new Date(record.endTime).toLocaleString() : '-';
                const duration = record.durationSeconds ? formatDuration(record.durationSeconds) : '-';

                return `
                    <div class="exercise-record-item">
                        <div class="exercise-record-header">
                            <span class="exercise-record-name">${record.exerciseName || '未知运动'}</span>
                            <span class="exercise-record-status ${record.status === '进行中' ? 'ongoing' : 'completed'}">${record.status}</span>
                        </div>
                        <div class="exercise-record-details">
                            <div class="exercise-record-detail">
                                <span class="exercise-record-label">开始时间:</span>
                                <span class="exercise-record-value">${startTime}</span>
                            </div>
                            <div class="exercise-record-detail">
                                <span class="exercise-record-label">结束时间:</span>
                                <span class="exercise-record-value">${endTime}</span>
                            </div>
                            <div class="exercise-record-detail">
                                <span class="exercise-record-label">运动时长:</span>
                                <span class="exercise-record-value">${duration}</span>
                            </div>
                            ${record.hasHeartRate !== false ? `
                            <div class="exercise-record-detail">
                                <span class="exercise-record-label">平均心率:</span>
                                <span class="exercise-record-value">${record.avgHeartRate ? record.avgHeartRate + ' bpm' : '-'}</span>
                            </div>
                            <div class="exercise-record-detail">
                                <span class="exercise-record-label">最大心率:</span>
                                <span class="exercise-record-value">${record.maxHeartRate ? record.maxHeartRate + ' bpm' : '-'}</span>
                            </div>
                            ` : ''}
                            ${record.hasSpeed ? `
                            <div class="exercise-record-detail">
                                <span class="exercise-record-label">平均速率:</span>
                                <span class="exercise-record-value">${record.avgSpeed ? record.avgSpeed + ' km/h' : '-'}</span>
                            </div>
                            <div class="exercise-record-detail">
                                <span class="exercise-record-label">最大速率:</span>
                                <span class="exercise-record-value">${record.maxSpeed ? record.maxSpeed + ' km/h' : '-'}</span>
                            </div>
                            ` : ''}
                        </div>
                    </div>
                `;
            }).join('');
        }

        function formatDuration(duration) {
            if (!duration) return '00:00:00';

            const hours = Math.floor(duration / 3600);
            const minutes = Math.floor((duration % 3600) / 60);
            const seconds = duration % 60;

            return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }

        function checkCurrentExercise() {
            if (!currentUser) {
                // 如果未登录，清空进行中的运动显示
                const ongoingContainer = document.getElementById('ongoingExercisesContainer');
                if (ongoingContainer) {
                    ongoingContainer.innerHTML = '';
                }
                return;
            }

            fetch(`/api/exercise-records/user/${currentUser.id}/status/进行中`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data.length > 0) {
                        // 显示所有进行中的运动
                        displayOngoingExercises(data.data);

                        // 如果当前不在运动页面，显示提示信息
                        if (document.getElementById('exerciseSection').classList.contains('hidden')) {
                            showOngoingExerciseNotification(data.data.length);
                        }
                    }
                })
                .catch(error => {
                    console.error('检查当前运动失败:', error);
                });
        }

        function showOngoingExerciseNotification(count) {
            // 创建或更新通知元素
            let notification = document.getElementById('ongoingExerciseNotification');
            if (!notification) {
                notification = document.createElement('div');
                notification.id = 'ongoingExerciseNotification';
                notification.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: #ff6b6b;
                    color: white;
                    padding: 15px 20px;
                    border-radius: 8px;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                    z-index: 1000;
                    cursor: pointer;
                    font-weight: bold;
                    max-width: 300px;
                `;
                document.body.appendChild(notification);
            }

            notification.innerHTML = `
                <div>🏃‍♂️ 您有 ${count} 项运动正在进行中</div>
                <div style="font-size: 12px; margin-top: 5px;">点击查看详情</div>
            `;

            // 点击通知跳转到运动页面
            notification.onclick = function () {
                showSection('exercise');
                this.remove();
            };

            // 5秒后自动隐藏通知
            setTimeout(() => {
                if (notification && notification.parentNode) {
                    notification.remove();
                }
            }, 5000);
        }

        function displayOngoingExercises(records) {
            const ongoingContainer = document.getElementById('ongoingExercisesContainer');
            if (!ongoingContainer) return;

            if (records.length === 0) {
                ongoingContainer.innerHTML = '';
                return;
            }

            ongoingContainer.innerHTML = records.map(record => {
                const startTime = new Date(record.startTime).toLocaleString();
                const duration = calculateDurationFromStart(record.startTime);

                return `
                    <div class="exercise-card ongoing" data-record-id="${record.id}">
                        <div class="exercise-header">
                            <h3>${record.exerciseName || '未知运动'}</h3>
                            <span class="status ongoing">进行中</span>
                        </div>
                        <div class="exercise-status">
                            <div class="status-item">
                                <span class="status-label">开始时间:</span>
                                <span class="status-value">${startTime}</span>
                            </div>
                            <div class="status-item">
                                <span class="status-label">运动时长:</span>
                                <span class="status-value" id="duration-${record.id}">${duration}</span>
                            </div>
                            <div class="status-item">
                                <span class="status-label">当前心率:</span>
                                <span class="status-value" id="heartRate-${record.id}">-- bpm</span>
                            </div>
                            <div class="status-item">
                                <span class="status-label">当前速率:</span>
                                <span class="status-value" id="speed-${record.id}">${record.hasSpeed ? '-- km/h' : '--'}</span>
                            </div>
                            <div class="status-item">
                                <span class="status-label">健康状态:</span>
                                <span class="status-value" id="healthStatus-${record.id}">--</span>
                            </div>
                        </div>
                        <div class="exercise-actions">
                            <button class="btn btn-danger" onclick="endExercise(${record.id})">结束运动</button>
                        </div>
                    </div>
                `;
            }).join('');

            // 为每个进行中的运动启动计时器和传感器模拟
            records.forEach(record => {
                startExerciseTimerForRecord(record.id, record.startTime);
                startSensorSimulationForRecord(record.id, record.hasSpeed, record.hasHeartRate);
            });
        }

        function calculateDurationFromStart(startTime) {
            const start = new Date(startTime);
            const now = new Date();
            const duration = Math.floor((now - start) / 1000);
            return formatDuration(duration);
        }

        function startExerciseTimerForRecord(recordId, startTime) {
            const timer = setInterval(() => {
                const durationElement = document.getElementById(`duration-${recordId}`);
                if (durationElement) {
                    const start = new Date(startTime);
                    const now = new Date();
                    const duration = Math.floor((now - start) / 1000);
                    durationElement.textContent = formatDuration(duration);
                } else {
                    clearInterval(timer);
                }
            }, 1000);
        }

        function startSensorSimulationForRecord(recordId, hasSpeed, hasHeartRate) {
            const sensorTimer = setInterval(() => {
                if (hasHeartRate) {
                    const heartRateElement = document.getElementById(`heartRate-${recordId}`);
                    const healthStatusElement = document.getElementById(`healthStatus-${recordId}`);
                    if (heartRateElement && healthStatusElement) {
                        const heartRate = Math.floor(Math.random() * 40) + 120; // 120-160 bpm
                        heartRateElement.textContent = `${heartRate} bpm`;

                        // 根据心率判断健康状态
                        const healthStatus = getHeartRateHealthStatus(heartRate);
                        healthStatusElement.textContent = healthStatus.text;
                        healthStatusElement.className = `status-value health-status ${healthStatus.class}`;
                    }
                }

                if (hasSpeed) {
                    const speedElement = document.getElementById(`speed-${recordId}`);
                    if (speedElement) {
                        const speed = (Math.random() * 10 + 5).toFixed(1); // 5-15 km/h
                        speedElement.textContent = `${speed} km/h`;
                    }
                }

                // 检查运动记录是否还存在
                const recordElement = document.querySelector(`[data-record-id="${recordId}"]`);
                if (!recordElement) {
                    clearInterval(sensorTimer);
                }
            }, 2000);
        }

        function getHeartRateHealthStatus(heartRate) {
            // 心率健康状态判断（基于一般成年人的心率范围）
            if (heartRate < 60) {
                return {
                    text: '心率过低',
                    class: 'danger'
                };
            } else if (heartRate >= 60 && heartRate <= 100) {
                return {
                    text: '心率正常',
                    class: 'normal'
                };
            } else if (heartRate > 100 && heartRate <= 120) {
                return {
                    text: '心率偏高',
                    class: 'warning'
                };
            } else if (heartRate > 120 && heartRate <= 140) {
                return {
                    text: '快到危险值',
                    class: 'caution'
                };
            } else if (heartRate > 140 && heartRate <= 160) {
                return {
                    text: '到达危险值',
                    class: 'danger'
                };
            } else {
                return {
                    text: '明显超过危险值',
                    class: 'critical'
                };
            }
        }

        function endExercise(recordId) {
            // 模拟运动数据
            const avgHeartRate = Math.floor(Math.random() * 40) + 120; // 120-160 bpm
            const maxHeartRate = avgHeartRate + Math.floor(Math.random() * 20) + 10; // 比平均值高10-30
            const avgSpeed = (Math.random() * 10 + 5).toFixed(1); // 5-15 km/h
            const maxSpeed = (parseFloat(avgSpeed) + Math.random() * 5 + 2).toFixed(1); // 比平均值高2-7

            fetch(`/api/exercise-records/${recordId}/end?avgHeartRate=${avgHeartRate}&maxHeartRate=${maxHeartRate}&avgSpeed=${avgSpeed}&maxSpeed=${maxSpeed}`, {
                method: 'POST'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('运动结束成功！');

                        // 移除对应的运动卡片
                        const recordElement = document.querySelector(`[data-record-id="${recordId}"]`);
                        if (recordElement) {
                            recordElement.remove();
                        }

                        // 重新加载运动记录
                        loadExerciseRecords();
                    } else {
                        alert('结束运动失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('结束运动失败:', error);
                    alert('结束运动失败，请重试');
                });
        }


    </script>
</body>

</html>